package com.hxl.tech.gateway.auth.aop;


import cn.hutool.core.collection.CollUtil;
import com.hxl.tech.gateway.auth.annotate.ApiPrivilege;
import com.hxl.tech.gateway.auth.context.ContextHolder;
import com.hxl.tech.gateway.auth.exception.AuthException;
import com.hxl.tech.gateway.common.constant.AppConstant;
import com.hxl.tech.gateway.common.constant.Result;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Aspect
@Order(0)
@Component
public class PrivilegeAop {

    @Around("@annotation(apiPrivilege)")
    public Object process(ProceedingJoinPoint point, ApiPrivilege apiPrivilege) throws Throwable {

        List<String> anyRole = Arrays.stream(apiPrivilege.anyRole()).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        String needRole = apiPrivilege.needRole();

        // 获取当前会话中用户角色
        String roleName = ContextHolder.getUserInfo().getRoleName();
        Boolean isAdmin = ContextHolder.getUserInfo().getIsAdmin();

        // 拥有任意权限即通过
        if (CollUtil.isNotEmpty(anyRole)) {
            if (!anyRole.contains(roleName)) {
                throw new AuthException(Result.E10010);
            }
        }

        // 必须有所有权限才通过
        if (StringUtils.isNotBlank(needRole)) {
            if (needRole.equals(AppConstant.ROLE_ADMIN) && !isAdmin) {
                throw new AuthException(Result.E10010);
            }
        }

        // 通过权限校验，放行
        return point.proceed();
    }

}
